﻿using System;
using System.IO;
using System.Drawing;

namespace Kwan.Helper.Bitmaps
{
    /// <summary>
    /// 图片处理类
    /// </summary>
    public class Cutter : IDisposable
    {
        #region 成员变量
        private string _DefPath;
        private int[] _WidthArray;
        private int[] _HeightArray;
        private string[] _PathArray;
        private bool _AutoZoom;
        private bool _NoCut;
        private string _WaterPath;
        private string _WaterString;
        #endregion

        #region 公共属性
        /// <summary>
        /// 必要属性，用于循环上传。example:"Upload\\Product"
        /// </summary>
        public string DefPath
        {
            get { return _DefPath; }
            set { _DefPath = value; }
        }
        public int[] WidthArray
        {
            get { return _WidthArray; }
            set { _WidthArray = value; }
        }
        public int[] HeightArray
        {
            get { return _HeightArray; }
            set { _HeightArray = value; }
        }
        /// <summary>
        /// 必要属性，用于循环上传
        /// </summary>
        public string[] PathArray
        {
            get { return _PathArray; }
            set { _PathArray = value; }
        }
        public bool AutoZoom
        {
            get { return _AutoZoom; }
            set { _AutoZoom = value; }
        }
        public bool NoCut
        {
            get { return _NoCut; }
            set { _NoCut = value; }
        }
        public string WaterPath
        {
            get { return _WaterPath; }
            set { _WaterPath = value; }
        }
        public string WaterString
        {
            get { return _WaterString; }
            set { _WaterString = value; }
        }
        #endregion

        #region 构造函数
        public Cutter()
        {
            //_WidthArray = new int[] { 144, 180, 640 };
            //_HeightArray = new int[] { 108, 135, 480 };
            //_PathArray = new string[] { "p144", "p180", "p640" };
            //_AutoCut = false;
        }

        public Cutter(string waterPath)
            : this()
        {
            _WaterPath = waterPath;
        }
        #endregion

        #region ZoomCutter 裁剪并缩放
        /// <summary>
        /// 裁剪并缩放
        /// </summary>
        /// <param name="fs">图像数据流</param>
        /// <param name="width">要裁剪的宽度</param>
        /// <param name="height">要裁剪的高度</param>
        /// <param name="path">存储路径</param>
        /// <returns>是否成功裁剪</returns>
        public bool ZoomCutter(Image initImage, int width, int height, string path)
        {
            try
            {
                //从文件获取原始图片，并使用流中嵌入的颜色管理信息
                //Image initImage = Bitmap.FromStream(fs, true);

                //原图宽高均小于模版，不作处理，直接保存
                if (initImage.Width <= width && initImage.Height <= height)
                {
                    initImage.Save(path, initImage.RawFormat);
                }
                else
                {
                    //模版的宽高比例
                    double templateRate = double.Parse(width.ToString()) / height;
                    //原图片的宽高比例
                    double initRate = double.Parse(initImage.Width.ToString()) / initImage.Height;

                    //原图与模版比例相等，直接缩放
                    if (templateRate == initRate)
                    {
                        //按模版大小生成最终图片
                        Image templateImage = new Bitmap(width, height);
                        Graphics templateG = Graphics.FromImage(templateImage);
                        templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                        templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        templateG.Clear(Color.White);
                        templateG.DrawImage(initImage, new Rectangle(0, 0, width, height), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel);
                        templateImage.Save(path, initImage.RawFormat);
                    }
                    //原图与模版比例不等，裁剪后缩放
                    else
                    {
                        //裁剪对象
                        Image pickedImage = null;
                        Graphics pickedG = null;

                        //定位
                        Rectangle fromR = new Rectangle(0, 0, 0, 0);//原图裁剪定位
                        Rectangle toR = new Rectangle(0, 0, 0, 0);//目标定位

                        //宽为标准进行裁剪
                        if (templateRate > initRate)
                        {
                            //裁剪对象实例化
                            pickedImage = new System.Drawing.Bitmap(initImage.Width, int.Parse(Math.Floor(initImage.Width / templateRate).ToString()));
                            pickedG = Graphics.FromImage(pickedImage);

                            //裁剪源定位
                            fromR.X = 0;
                            fromR.Y = int.Parse(Math.Floor((initImage.Height - initImage.Width / templateRate) / 2).ToString());
                            fromR.Width = initImage.Width;
                            fromR.Height = int.Parse(Math.Floor(initImage.Width / templateRate).ToString());

                            //裁剪目标定位
                            toR.X = 0;
                            toR.Y = 0;
                            toR.Width = initImage.Width;
                            toR.Height = int.Parse(Math.Floor(initImage.Width / templateRate).ToString());
                        }
                        //高为标准进行裁剪
                        else
                        {
                            pickedImage = new System.Drawing.Bitmap(int.Parse(Math.Floor(initImage.Height * templateRate).ToString()), initImage.Height);
                            pickedG = Graphics.FromImage(pickedImage);

                            fromR.X = int.Parse(Math.Floor((initImage.Width - initImage.Height * templateRate) / 2).ToString());
                            fromR.Y = 0;
                            fromR.Width = int.Parse(Math.Floor(initImage.Height * templateRate).ToString());
                            fromR.Height = initImage.Height;

                            toR.X = 0;
                            toR.Y = 0;
                            toR.Width = int.Parse(Math.Floor(initImage.Height * templateRate).ToString());
                            toR.Height = initImage.Height;
                        }

                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                        //裁剪
                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);

                        //按模版大小生成最终图片
                        Image templateImage = new System.Drawing.Bitmap(width, height);
                        Graphics templateG = Graphics.FromImage(templateImage);
                        templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                        templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        templateG.Clear(Color.White);
                        templateG.DrawImage(pickedImage, new Rectangle(0, 0, width, height), new Rectangle(0, 0, pickedImage.Width, pickedImage.Height), GraphicsUnit.Pixel);
                        templateImage.Save(path, initImage.RawFormat);

                        //释放资源
                        templateG.Dispose();
                        templateImage.Dispose();

                        pickedG.Dispose();
                        pickedImage.Dispose();
                    }
                }
                //释放资源
                //initImage.Dispose();
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion

        #region RateCutter 按宽比例裁剪
        /// <summary>
        /// 按宽比例裁剪
        /// </summary>
        /// <param name="initImage">要裁剪的图像</param>
        /// <param name="width">宽度</param>
        /// <param name="path">高度</param>
        /// <returns>是否成功裁剪</returns>
        public bool RateCutter(Image initImage, int width, string path)
        {
            //从文件获取原始图片，并使用流中嵌入的颜色管理信息
            //Image initImage = Bitmap.FromStream(fs, true);
            try
            {
                //原图宽高均小于模版，不作处理，直接保存
                if (initImage.Width <= width)
                {
                    initImage.Save(path, initImage.RawFormat);
                }
                else
                {
                    int templateHeight = width * initImage.Height / initImage.Width;

                    //按模版大小生成最终图片
                    Image templateImage = new Bitmap(width, templateHeight);
                    Graphics templateG = Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(initImage, new Rectangle(0, 0, width, templateHeight), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel);
                    templateImage.Save(path, initImage.RawFormat);

                    //释放资源
                    templateG.Dispose();
                    templateImage.Dispose();

                }
                //释放资源
                //initImage.Dispose();
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion

        #region UploadImage 上传图像
        /// <summary>
        /// 上传图像
        /// </summary>
        /// <param name="fs">图像数据流</param>
        /// <param name="defPath">默认路径（例：Upload\\Product）</param>
        /// <param name="newName">图片名称</param>
        /// <returns>图片名称</returns>
        public string UploadImage(Stream fs, string newName)
        {
            string FileName = string.Empty;
            try
            {
                if (fs.Length == 0) return FileName;
                //获取根目录
                string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                FileName = string.IsNullOrEmpty(newName) ? Guid.NewGuid().ToString("N") + ".jpg" : newName;

                //从文件获取原始图片，并使用流中嵌入的颜色管理信息
                Image initImage = Bitmap.FromStream(fs, true);

                //加入图片水印
                if (_WaterPath != null)
                {
                    WaterPoint point = WaterPoint.Create(2, 2, WaterPoint.PointType.RightBottom);
                    using (Watermark imageWater = new Watermark(_WaterPath, 0.6f, point))
                    {
                        initImage = imageWater.Mark(initImage);
                    }
                }
                //加入文字水印
                if (!string.IsNullOrEmpty(WaterString))
                {
                    WaterPoint point = WaterPoint.Create(2, 2, WaterPoint.PointType.RightBottom);
                    using (Watermark imageWater =
                        new Watermark(_WaterString, "宋体", false, Color.Blue, point))
                    {
                        initImage = imageWater.Mark(initImage);
                    }
                }

                //循环上传
                for (int i = 0; i < _PathArray.Length; ++i)
                {
                    string path = Path.Combine(solutionPath + _DefPath + "\\" + _PathArray[i] + "\\");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    //不裁剪上传
                    if (_NoCut)
                    {
                        ZoomCutter(initImage, initImage.Width, initImage.Height, path + FileName);
                        break;
                    }
                    //是否自动裁剪
                    if (!_AutoZoom)
                    {

                        RateCutter(initImage, _WidthArray[i], path + FileName);
                    }
                    else
                    {
                        ZoomCutter(initImage, _WidthArray[i], _HeightArray[i], path + FileName);
                    }
                }
                initImage.Dispose();
            }
            catch
            {
                //FileName
            }
            return FileName;
        }
        #endregion

        #region 删除图像
        /// <summary>
        /// 删除图像
        /// </summary>
        /// <param name="defPath">默认路径（例：Upload\\Product）</param>
        /// <param name="name">图片名称</param>
        public void DeleteFile(string defPath, string name)
        {
            string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
            for (int i = 0; i < _PathArray.Length; ++i)
            {
                string path = Path.Combine(solutionPath + defPath + "\\" + _PathArray[i] + "\\" + name);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
        }
        #endregion

        #region IDisposable 成员
        public void Dispose()
        {
            //if (_WaterPath == null) return;
            //_WaterPath.Close();
            //_WaterPath = null;
        }

        ~Cutter()
        {
            Dispose();
        }
        #endregion
    }
}
